﻿using HY.Utility.Enum;
using HY.Utility.ImportExport;
using HY.Utility.Match;
using HYDataCapture.Views;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HYDataCapture.Presenters
{
    public class AliexpressShopAllGoodsCapturePresenter
    {
        private IAliexpressShopAllGoodsCaptureView _View;

        public AliexpressShopAllGoodsCapturePresenter(IAliexpressShopAllGoodsCaptureView view)
        {
            _View = view;
            _View.GoodsTags = EnumAttributeHelper.GetEnumDescription(typeof(Enums.AliexpressGoodsTagEnum)).ToArray();
            Data = new DataTable();
        }

        public Enums.CaptureStateEnum DataCapture()
        {
            var output = Enums.CaptureStateEnum.NoMatch;
            do
            {
                if (_View.SelectGoodsTags.Length == 0)
                {
                    _View.Log = "未选中任何商品Tag，无法采集";
                    break;
                }
                string html = _View.DataHtml;

                List<Enums.AliexpressGoodsTagEnum> tagList = new List<Enums.AliexpressGoodsTagEnum>();
                foreach (var tag in _View.SelectGoodsTags)
                {
                    tagList.Add(EnumAttributeHelper.GetEnumValueFromDescription<Enums.AliexpressGoodsTagEnum>(tag));
                    if (Data.Columns.IndexOf(tag) == -1)
                        Data.Columns.Add(tag, typeof(string));
                }

                HtmlElementMatcher matcher = new HtmlElementMatcher(html);
                //bool isEnd = false;

                //bool isLazyLoading = false;
                //data-ks-lazyload
                HtmlElementMatcher.SelectNodesEventHandler handler2 = (index, items, outerhtml) => {
                    var matcher2 = new HtmlElementMatcher(outerhtml);
                    DataRow row = Data.NewRow();
                    for (var i = 0; i < tagList.Count; ++i)
                    {
                        string value = "";
                        switch (tagList[i])
                        {
                            case Enums.AliexpressGoodsTagEnum.Id:
                                {
                                    value = matcher2.GetNodeAttributeValue("//div[@class='info']/input[@class='atc-product-id']", "value");
                                }
                                break;
                            case Enums.AliexpressGoodsTagEnum.Title:
                                {
                                    value = matcher2.GetNodeInnerText("//div[@class='detail']/h3/a");
                                    if (value.IndexOf("\"") == -1)
                                    {
                                        value = matcher2.GetNodeAttributeValue("//div[@class='detail']/h3/a", "title");
                                    }
                                }
                                break;
                            case Enums.AliexpressGoodsTagEnum.Link:
                                {
                                    value = matcher2.GetNodeAttributeValue("//div[@class='detail']/h3/a", "href");
                                    if (!value.StartsWith("http:") && !value.StartsWith("https:"))
                                        value = "http:" + value;
                                }
                                break;
                            case Enums.AliexpressGoodsTagEnum.ImageLink:
                                {
                                    value = matcher2.GetNodeAttributeValue("//div[@class='pic']/a/img", "src");
                                    if (string.IsNullOrEmpty(value))
                                        value = matcher2.GetNodeAttributeValue("//div[@class='pic']/a/img", "image-src");
                                    if (!value.StartsWith("http:") && !value.StartsWith("https:"))
                                        value = "http:" + value;
                                }
                                break;
                            case Enums.AliexpressGoodsTagEnum.Price:
                                {
                                    value = matcher2.GetNodeInnerText("//div[@class='cost']/b").Trim();
                                    value = value.Replace("US $", "");
                                }
                                break;
                            case Enums.AliexpressGoodsTagEnum.SaleNum:
                                {
                                    value = matcher2.GetNodeInnerText("//div[@class='recent-order']");
                                    var m = Regex.Match(value, @"\d+");
                                    if(m.Success)
                                    {
                                        value = m.Value;
                                    }
                                }
                                break;
                            case Enums.AliexpressGoodsTagEnum.Discount:
                                {
                                    value = matcher2.GetNodeInnerText("//div[@class='discount']/span[@class='rate']");
                                }
                                break;
                        }
                        row[i] = value;
                    }
                    Data.Rows.Add(row);
                };

                matcher.GetNodesAttributeValues(handler2, "//div[@class='ui-box-body']/ul/li");

                NextUrl = matcher.GetNodeAttributeValue("//a[contains(text(),'Next')]", "href");
                if (!string.IsNullOrEmpty(NextUrl))
                {
                    if (!NextUrl.StartsWith("http:") && !NextUrl.StartsWith("https:"))
                        NextUrl = "https:" + NextUrl;
                    output = Enums.CaptureStateEnum.Success;
                }
                else
                    output = Enums.CaptureStateEnum.Completed;
            } while (false);
            SetSalesAmount();
            return output;
        }

        private bool CheckSaleNumPriceTagExists()
        {
            bool output = false;
            do
            {
                if (!Data.Columns.Contains(Enums.AliexpressGoodsTagEnum.SaleNum.GetEnumDescription()))
                {
                    break;
                }
                if (!Data.Columns.Contains(Enums.AliexpressGoodsTagEnum.Price.GetEnumDescription()))
                {
                    break;
                }
                output = true;
            } while (false);
            return output;
        }

        private void SetSalesAmount()
        {
            var output = "";
            do
            {
                if (Data.Columns.Count == 0)
                    break;
                if (!CheckSaleNumPriceTagExists())
                    break;

                var total = 0m;
                var temp = 0m;
                foreach (DataRow row in Data.Rows)
                {
                    if (!decimal.TryParse(Convert.ToString(row[Enums.AliexpressGoodsTagEnum.SaleNum.GetEnumDescription()]), out temp))
                        continue;
                    var saleNum = temp;
                    if (!decimal.TryParse(Convert.ToString(row[Enums.AliexpressGoodsTagEnum.Price.GetEnumDescription()]), out temp))
                        continue;
                    var price = temp;
                    total += (price * saleNum);
                }
                output = total.ToString();
            } while (false);
            _View.SaleAmount = output;
        }

        public void ExportExcel(string fileName)
        {
            try
            {
                if (Data == null)
                {
                    _View.Log = "没有数据可供导出";
                    return;
                }
                _View.Log = "正在导出...";
                using (var helper = new ExcelHelper(fileName))
                {
                    helper.DataTableToExcel(Data, "导出数据", true);
                }
                _View.Log = "已导出：" + fileName;
            }
            catch (Exception ex)
            {
                _View.Log = "导出出错：" + ex.Message;
            }
        }
        public void ExportExcelWithGoodsImage(string fileName)
        {
            try
            {
                do
                {
                    if (Data == null)
                    {
                        _View.Log = "没有数据可供导出";
                        break;
                    }
                    var tag = Enums.AliexpressGoodsTagEnum.ImageLink.GetEnumDescription();
                    var index = Data.Columns.IndexOf(tag);
                    if (index == -1)
                    {
                        _View.Log = "不存在Tag，无法导出：" + tag;
                        break;
                    }
                    _View.Log = "正在导出...";
                    using (var helper = new ExcelHelper(fileName))
                    {
                        helper.DataTableToExcel(Data, new List<int>(new int[] { index }));
                    }
                    _View.Log = "已导出：" + fileName;
                } while (false);
            }
            catch (Exception ex)
            {
                _View.Log = "导出出错：" + ex.Message;
            }
        }

        public string NextUrl { get; private set; }
        public DataTable Data { get; private set; }
    }
}
